package com.xjg.dynconfig;

import java.util.Map;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.xjg.framework.common.zookeeper.ZKListener;

public class PushConfigListener implements ZKListener {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private String path;

	public PushConfigListener(String path) {
		this.path = path;

	}

	public void executor(CuratorFramework client) {

		// 使用Curator的NodeCache来做ZNode的监听，不用我们自己实现重复监听
		final NodeCache cache = new NodeCache(client, path);
		cache.getListenable().addListener(new NodeCacheListener() {

			public void nodeChanged() throws Exception {

				byte[] data = cache.getCurrentData().getData();

				// 重置数据
				if (data != null) {
					String config = new String(data);
					PushConfigs.pushConfigs = JSON
							.parseObject(config, Map.class);
				}
			}
		});
		try {
			cache.start(true);
		} catch (Exception e) {
			logger.error("Start NodeCache error for path: {}, error info: {}",
					path, e.getMessage());
		}
	}
}
